<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Closure Example</title>
    <style>
       .button {
            margin: 5px;
            padding: 10px;
            border: 1px solid #000;
            cursor: pointer;
        }
    .selected {
            background-color: yellow;
        }
    </style>
</head>

<body>
    <div>
        <button class="button" id="button1">按钮1</button>
        <button class="button" id="button2">按钮2</button>
        <button class="button" id="button3">按钮3</button>
    </div>
    <div id="status"></div>

    <script>
        // 一个工厂函数，用于创建处理按钮点击的闭包
        function createButtonHandler(index) {
            return function () {
                // 弹出按钮下标
                alert(`${index}`);
                updateStatus(index);
            };              
        }

        // 更新 UI 以显示哪个按钮被选中
        function updateStatus(selectedIndex) {
            // 移除所有按钮的'selected'类
            document.querySelectorAll('.button').forEach((button, index) => {
                if (index!== selectedIndex) {
                    button.classList.remove('selected');
                }
            });
            // 为选中的按钮添加'selected'类
            document.querySelectorAll('.button')[selectedIndex].classList.add('selected');
        }

        // 为每个按钮添加事件监听器
        document.getElementById('button1').addEventListener('click', createButtonHandler(0));
        document.getElementById('button2').addEventListener('click', createButtonHandler(1));
        document.getElementById('button3').addEventListener('click', createButtonHandler(2));
    </script>
</body>

</html>